const mysql = require('mysql2/promise');
const jwt = require('jsonwebtoken');
const { secret } = require('../config/jwt');

async function diagnoseBookshelf() {
  console.log('🔍 开始诊断书架功能...\n');

  // 1. 检查数据库连接
  let connection;
  try {
    connection = await mysql.createConnection({
      host: process.env.DB_HOST || 'localhost',
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || '',
      database: process.env.DB_NAME || 'uni_library'
    });
    console.log('✅ 数据库连接成功');
  } catch (error) {
    console.log('❌ 数据库连接失败:', error.message);
    return;
  }

  try {
    // 2. 检查数据库表
    console.log('\n📋 检查数据库表...');
    const tables = ['books', 'bookshelf', 'users'];
    for (const table of tables) {
      try {
        const [rows] = await connection.execute(`SELECT COUNT(*) as count FROM ${table}`);
        console.log(`✅ 表 ${table} 存在，记录数: ${rows[0].count}`);
      } catch (error) {
        console.log(`❌ 表 ${table} 检查失败:`, error.message);
      }
    }

    // 3. 检查用户
    console.log('\n👤 检查用户...');
    const [users] = await connection.execute('SELECT id, username FROM users LIMIT 1');
    if (users.length === 0) {
      console.log('❌ 没有用户数据');
      return;
    }
    const user = users[0];
    console.log(`✅ 找到用户: ${user.username} (ID: ${user.id})`);

    // 4. 检查图书
    console.log('\n📚 检查图书...');
    const [books] = await connection.execute('SELECT id, name FROM books LIMIT 5');
    console.log(`✅ 找到 ${books.length} 本图书`);
    books.forEach(book => console.log(`  - ID: ${book.id}, 名称: ${book.name}`));

    // 5. 生成测试token
    console.log('\n🔑 生成测试token...');
    const token = jwt.sign(
      {
        userId: user.id,
        userType: 'student',
        isAdmin: false,
        phone: '13800138000',
        username: user.username
      },
      secret,
      { expiresIn: '1h' }
    );
    console.log('✅ Token生成成功');

    // 6. 模拟API调用
    console.log('\n🚀 模拟API调用...');

    // 模拟认证中间件
    try {
      const decoded = jwt.verify(token, secret);
      console.log('✅ Token验证成功:', decoded);
    } catch (error) {
      console.log('❌ Token验证失败:', error.message);
      return;
    }

    // 模拟书架添加逻辑
    if (books.length > 0) {
      const testBook = books[0];
      console.log(`\n📖 测试添加图书到书架: ${testBook.name} (ID: ${testBook.id})`);

      // 检查图书是否存在
      const [bookCheck] = await connection.execute('SELECT id, name FROM books WHERE id = ?', [testBook.id]);
      console.log('📖 图书存在检查:', bookCheck.length > 0 ? '✅' : '❌');

      // 检查是否已在书架中
      const [existing] = await connection.execute(
        'SELECT id FROM bookshelf WHERE user_id = ? AND book_id = ?',
        [user.id, testBook.id]
      );
      console.log('📖 书架重复检查:', existing.length > 0 ? '⚠️ 已存在' : '✅ 可以添加');

      if (existing.length === 0) {
        // 尝试添加
        try {
          await connection.execute(
            'INSERT INTO bookshelf (user_id, book_id) VALUES (?, ?)',
            [user.id, testBook.id]
          );
          console.log('✅ 书架添加成功');
        } catch (error) {
          console.log('❌ 书架添加失败:', error.message);
        }
      }
    }

    console.log('\n🎉 诊断完成！');

  } catch (error) {
    console.error('❌ 诊断过程中出错:', error);
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

// 运行诊断
diagnoseBookshelf().catch(console.error);
